<?php

namespace app\admin\controller;

use app\common\model\Oauth;
use app\common\model\Payment;
use app\common\model\User;
use app\common\model\UserBalanceLog;
use helper\util\Str;
use think\facade\Db;
use think\facade\View;

class UserBalanceLogController extends AdminBaseController
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['user_id'])) {
                $where[] = ['user_id', '=', $param['user_id']];
            }
            if (!empty($param['type'])) {
                $where[] = ['type', '=', $param['type']];
            }
            $list = UserBalanceLog::where($where)->order('id desc')->paginate(10);
            return $this->result($list->items(), '', ['count' => $list->total()]);
        }
        return View::fetch('finance/balance_log');
    }

    public function recharge_list()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $list = UserBalanceLog::getList($param);
            return $this->result([], '', $list);
        }
        return View::fetch('finance/recharge_list');
    }

    public function transfer_list()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $list = UserBalanceLog::getList($param);
            return $this->result([], '', $list);
        }
        return View::fetch('finance/recharge_list');
    }

    public function save()
    {
        $param             = $this->request->param();
        $param['admin_id'] = $this->user_id;
        $param['type']     = 0;
        $param['payment']  = 2;
        $param['status']   = 1;
        $user              = User::field('id,name,mobile')->find($param['user_id']);
        if (!$user) {
            $this->error("用户不存在");
        }
        $this->validate($param, 'app\common\validate\Transfer');
        $account = UserBalanceLog::create($param);
        User::change($account['user_id'], $account['amount']);

        // 消息
        //Push::message($account['user_id'], '余额充值', '充值金额' . $account['amount']);

        $account['user'] = $user;
        $this->success('操作成功', $account);
    }

    /**
     * 详情
     *
     */
    public function read($id)
    {
        $data = UserBalanceLog::where(['user_id' => $this->user_id, 'id' => $id])->find();
        $this->success('获取成功！', $data);
    }

    /**
     * @OA\Put(path="/account/cancel/{id}",tags={"提现"},summary="取消提现",
     *   @OA\Parameter(name="authorization", in="header", description="Bearer token", @OA\Schema(type="string")),
     *   @OA\Parameter(name="id", in="path", description="id", @OA\Schema(type="int")),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function cancel($id)
    {
        $userId = $this->user_id;
        $data   = [
            'id'      => $id,
            'user_id' => $userId,
            'status'  => -1
        ];
        $result = UserBalanceLog::update($data);
        if ($result) {
            $this->success('取消成功！');
        } else {
            $this->error('取消失败！');
        }
    }

    /**
     * @OA\Put(path="/account/{id}/status",tags={"提现"},summary="审核",
     *   @OA\Parameter(name="authorization", in="header", description="Bearer token", @OA\Schema(type="string")),
     *   @OA\Parameter(name="id", in="path", description="id", @OA\Schema(type="int")),
     *   @OA\RequestBody(
     *     @OA\MediaType(mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="状态", property="status", type="integer"),
     *           @OA\Property(description="备注", property="admin_note", type="varchar"),
     *           required={"status"})
     *       )
     *     ),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function status($id)
    {
        $param             = $this->request->param();
        $param['id']       = $id;
        $param['status']   = $param['status'] ?? 1;
        $param['admin_id'] = $this->user_id;
        $account           = UserBalanceLog::find($id);

        if ($account['status'] != 0) {
            $this->error("请勿重复操作");
        }

        if ($param['status'] == 1) {
            // 调用支付接口
            if ($account['payment'] == 4) {
                $user = User::where('id', $account['user_id'])->value('name');
                if (!$user) {
                    $this->error("未实名认证");
                }
                $oauth = Oauth::getAccount($account['user_id']);
                if (!isset($oauth['alipay'])) {
                    $this->error("未绑定支付宝账号");
                }
                $pay = Payment::alipay();
                $res = $pay->transfer((string)$account['id'], $account['amount'], $oauth['alipay'], $user, '余额提现');
                if (!$res) {
                    $this->error("支付宝提现失败");
                }
            } else {
                $this->error("暂不支持微信提现");
            }
            User::change($account['user_id'], $account['amount'], 1, '余额提现');
        }
        $data = $account->save($param);
        if (!$data) {
            $this->error("操作失败");
        }
        $this->success('操作成功', $data);
    }

    /**
     * @OA\Post(path="/account/pay",tags={"充值"},summary="充值",
     *   @OA\Parameter(name="authorization", in="header", description="Bearer token", @OA\Schema(type="string")),
     *   @OA\RequestBody(
     *     @OA\MediaType(mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="手机号码", property="mobile", type="string"),
     *           @OA\Property(description="支付方式:4支付宝5微信", property="payment", type="integer"),
     *           @OA\Property(description="金额", property="amount", type="numbeer"),
     *           @OA\Property(description="订单号", property="out_trade_no", type="string"),
     *           required={"payment","amount"})
     *       )
     *     ),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function pay()
    {
        $param     = $this->request->param();
        $user_id   = $this->user_id;
        $payment   = $param['payment'] ?? 4;

        if ($param['payment'] == 1) {
            $len = strlen($param['out_trade_no']);
            if ($len == 18) {
                //
            } else {
                //
            }
            $this->success('支付成功');
        }

        $user_note = $payment == 4 ? '支付宝充值' : '微信充值';
        if (!empty($param['mobile'])) {
            $user_id = User::where('mobile', $param['mobile'])->value('id');
            if (!$user_id) {
                $this->error('用户不存在！');
            }
            $user_note .= "(代充值)";
        }

        $out_trade_no = $param['out_trade_no'] ?? Str::getOrderSN();
        $amount  = round($param['amount'], 2);
        $account = UserBalanceLog::create([
            'user_id'      => $user_id,
            'amount'       => $amount,
            'out_trade_no' => $out_trade_no,
            'payment'   => $payment,
            'user_note' => $user_note,
            'type'      => 0,
        ]);
        $name = $payment == 4 ? 'alipay' : 'wxpay';
        //$pay  = Payment::factory($name, Payment::getConf($name))->app('余额充值', $out_trade_no, $amount);
        //$this->success('调用成功', ['order' => $account, 'pay' => $pay]);
    }

    /**
     * @OA\Post(path="/account/transfer",tags={"提现"},summary="转账",
     *   @OA\Parameter(name="authorization", in="header", description="Bearer token", @OA\Schema(type="string")),
     *   @OA\RequestBody(
     *     @OA\MediaType(mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="手机号码", property="mobile", type="string"),
     *           @OA\Property(description="金额", property="amount", type="numbeer"),
     *           @OA\Property(description="备注", property="user_note", type="integer"),
     *           required={"mobile","amount"})
     *       )
     *     ),
     *   @OA\Response(response="200", description="successful operation")
     * )
     */
    public function transfer()
    {
        $param              = $this->request->param();
        $param['user_note'] = $param['user_note'] ?? '';

        if ($this->user->balance < $param['amount']) {
            $this->error("请输入正确的转账金额!");
        }
        if ($param['user_id'] == $this->user_id) {
            $this->error("收款人不能是自己!");
        }
        $friend = User::where('mobile', $param['mobile'])->find();
        if (empty($friend)) {
            abort(404, '收款人不存在!');
        }

        //自己余额减少
        UserBalanceLog::create([
            'user_id'   => $this->user_id,
            'old_money' => $this->user->balance,
            'money'     => $param['amount'],
            'now_money' => $this->user->balance - $param['amount'],
            'type'      => 1,
            'remark'    => $param['user_note'],
        ]);
        $this->user->balance = Db::raw('balance-' . $param['amount']);
        $this->user->save();

        //对方余额增加
        UserBalanceLog::create([
            'user_id' => $param['user_id'],
            'old_money' => $friend['balance'],
            'money'     => $param['amount'],
            'now_money' => $friend['balance'] + $param['amount'],
            'type'    => 1,
            'remark'  => $param['user_note'],
        ]);
        $friend->balance = Db::raw('balance+' . $param['amount']);
        $friend->save();

        $this->success('操作成功');
    }
}